<script setup>
import { onHide, onLaunch, onShow } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import { useMainStore } from '@/store/store';
const main = useMainStore();
import { isWeixin, parseQuery } from '@/utils/util';
import cookie from '@/utils/cookie';
import { userAuthSession, wechatAuth, DoUserInfo } from '@/api/auth';
import { APP_ID } from '@/config';
import { watch, onMounted } from 'vue';
const { currentLanguageTexts, tgUser } = storeToRefs(main);
import { getLanguageList } from '@/api/user';

const sys = uni.getSystemInfoSync();

onLaunch(async () => {
  let { list } = await getLanguageList();
  list.forEach((el) => {
    el.key = el.code;
    el.label = el.name;
  });
  main.languageTypes = list || [];
  // 处理iOS Safari的特殊格式
  let defaultLanguage = 'zh-CN';
  if (sys.platform === 'ios') {
    defaultLanguage = sys.language.replace(/_/g, '-');
  } else {
    defaultLanguage = sys.language;
  }
  if (
    defaultLanguage.indexOf('zh') !== -1 ||
    defaultLanguage.indexOf('cn') >= 0
  ) {
    defaultLanguage = 'zh-CN';
  }
  if (defaultLanguage == 'en') {
    defaultLanguage = 'en';
  }
  if (
    main.currentLanguage?.key === 'cn' ||
    main.currentLanguage?.key == 'khmer'
  ) {
    main.isManualSetLang = false;
  }

  if (!main.isManualSetLang) {
    // const defaultLanguage = navigator.language.toLowerCase()
    main.isManualSetLang = true;
    main.currentLanguage = list.find(
      (item) => item.code === defaultLanguage
    ) || { key: 'zh-CN', label: '中文' };
  }
});

onShow(() => {
  // 检查用户登录情况
  // #ifdef H5
  if (isWeixin()) {
    // H5编译的代码
    // 判断是否是微信浏览器
    // oAuth();
    //return;
  }
  // #endif
  // #ifdef MP-WEIXIN
  wechatMiniLogin();
  // #endif
});

onHide(() => {
  console.log('App Hide');
});

const wechatMiniLogin = () => {
  //this.$u.toast('登录中');
  uni
    .login({
      provider: 'weixin',
    })
    .then(async (res) => {
      let data = await userAuthSession({
        code: res.code,
      });
      if (data) {
        console.log('data.openId:', data.openId);
        main.SET_OPENID(data.openId);
        if (
          data.hasOwnProperty('userInfo') &&
          data.accessToken &&
          data.accessToken != ''
        ) {
          main.SET_MEMBER(data.userInfo);
          main.SET_TOKEN(data.accessToken);
        }
      }
    });
};

const getAuthUrl = (appId) => {
  // #ifdef H5
  // #endif
  cookie.set('redirect', window.location.href);
  const url = `${location.origin}/h5/#/pages/index/index`;
  cookie.set('index_url', url);
  let redirect_uri = encodeURIComponent(url);

  const state = 'STATE';
  return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
};

const oAuth = async () => {
  const WX_AUTH = 'wx_auth';
  return new Promise((resolve, reject) => {
    const accessToken = uni.getStorageSync('accessToken');
    if (cookie.has('wx_auth') && accessToken && main.isLogin) {
      reject();
      return;
    }
    const { code } = parseQuery();
    if (!code) {
      //公众号appid
      const appid = APP_ID;
      location.href = getAuthUrl(appid);
      return;
    } else {
      auth(code);
    }
    resolve();
  }).catch((error) => {
    console.log(error);
  });
};

const auth = async (code) => {
  console.log('获取微信授权:', code);
  let data = await wechatAuth({ code: code });
  cookie.set('wx_auth', code);
  if (data) {
    main.SET_OPENID(data.openId);
    main.SET_MEMBER(data.userInfo);
    main.SET_TOKEN(data.accessToken);

    let newParams = cookie.get('params');
    if (newParams) {
      uni.navigateTo({
        url: '/pages/components/pages/scan/scan',
      });
    }
  }
};

watch(
  () => currentLanguageTexts.value,
  (nv) => {
    uni.setTabBarItem({
      index: 0,
      text: currentLanguageTexts.value.homePage,
    });
    uni.setTabBarItem({
      index: 1,
      text: nv.orderingMeal,
    });
    uni.setTabBarItem({
      index: 2,
      text: nv.menuOrder,
    });
    uni.setTabBarItem({
      index: 3,
      text: nv.mine,
    });
  },
  { deep: true }
);
onMounted(async () => {
  console.log(window.Telegram, 112);
  const tgInfo = window.Telegram.WebApp;
  const param = {
    chat_id: tgInfo.initDataUnsafe.user.id,
    user_name: tgInfo.initDataUnsafe.user.username,
    query_id: tgInfo.initDataUnsafe.query_id,
    last_name: tgInfo.initDataUnsafe.user.last_name,
    first_name: tgInfo.initDataUnsafe.user.first_name,
    language_code: tgInfo.initDataUnsafe.user.language_code,
    allows_write_to_pm: tgInfo.initDataUnsafe.user.allows_write_to_pm,
    photo_url: tgInfo.initDataUnsafe.user.photo_url,
    auth_date: tgInfo.initDataUnsafe.auth_date,
    signature: tgInfo.initDataUnsafe.signature,
    hash: tgInfo.initDataUnsafe.hash,
    version: tgInfo.version,
    platform: tgInfo.platform,
    // chat_id: '1166923618',
    // user_name: 'hao123',
    // query_id: '1166923618',
    // last_name: 'guoli',
    // first_name: 'zhang',
    // language_code: 'zh-hans',
    // allows_write_to_pm: '',
    // photo_url: '',
    // auth_date: '',
    // signature: '',
    // hash: '',
    // version: '8.0',
    // platform: '',
  };
  tgUser.value = param;

  // alert(JSON.stringify(param))
  const res = await DoUserInfo(param);
  console.log(res, 2222);
});
</script>

<style lang="scss">
@import '~@/static/style/app.scss';
//@import 'static/iconfont/iconfont.scss';
//@import url('./static/style/style.less');
@import 'static/style/yshop.css';

// /*每个页面公共css */
// page {
//   background-color: #f5f5f5;
// }
</style>
